<template>
	<view class="container">
		<view class="input-group">
			<view class="input-item">
				<text class="label">最小数值</text>
				<input 
					type="number" 
					v-model="minNumber" 
					class="input" 
					placeholder="默认为0"
					@blur="validateMinNumber"
				/>
			</view>
			<view class="input-item">
				<text class="label">最大数值</text>
				<input 
					type="number" 
					v-model="maxNumber" 
					class="input" 
					placeholder="默认为10"
					@blur="validateMaxNumber"
				/>
			</view>
			<view class="input-item">
				<text class="label">生成个数</text>
				<input 
					type="number" 
					v-model="count" 
					class="input" 
					placeholder="默认为1"
					@blur="validateCount"
				/>
			</view>
		</view>

		<view class="number-display">
			<text class="number" v-if="!currentNumbers.length">点击下方按钮生成随机数</text>
			<view v-else class="number-list">
				<text class="number" v-for="(num, index) in currentNumbers" :key="index">{{num}}</text>
			</view>
		</view>
		
		<view class="usage-info">
			<text class="usage-text">今日剩余免费次数：{{remainingUses}}</text>
		</view>
		
		<view class="button-group">
			<button class="btn generate" @click="handleGenerateClick">生成随机数</button>
			<button class="btn reset" @click="resetNumber">重置</button>
			<button class="btn history" @click="goToHistory">查看历史</button>
		</view>
		
		<!-- #ifdef MP-TOUTIAO -->
		<view class="ad-container">
			<ad unit-id="shffbjl7cda8hw9x7z" type="feed"></ad>
		</view>
		<!-- #endif -->
		
		<!-- 底部广告位 -->
		<!-- <view class="ad-container">
			<text class="ad-text">广告位预留</text>
		</view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				minNumber: '0',
				maxNumber: '10',
				count: '1',
				currentNumbers: [],
				history: [],
				remainingUses: 3, // 每天剩余使用次数
				lastUseDate: '', // 上次使用日期
				rewardedVideoAd: null // 激励视频广告实例
			}
		},
		onLoad() {
			// 从本地存储加载历史记录
			const history = uni.getStorageSync('numberHistory') || []
			this.history = history
			
			// 检查并初始化每日使用次数
			this.initDailyUses()
			
			// 初始化激励视频广告
			// #ifdef MP-TOUTIAO
			this.initRewardedVideoAd()
			// #endif
		},
		methods: {
			initDailyUses() {
				const today = new Date().toDateString()
				const lastUseDate = uni.getStorageSync('lastUseDate')
				const remainingUses = uni.getStorageSync('remainingUses')
				
				if (lastUseDate !== today) {
					// 新的一天，重置使用次数
					this.remainingUses = 3
					this.lastUseDate = today
					uni.setStorageSync('lastUseDate', today)
					uni.setStorageSync('remainingUses', 3)
				} else {
					// 同一天，使用存储的次数
					this.remainingUses = remainingUses || 0
					this.lastUseDate = lastUseDate
				}
			},
			// #ifdef MP-TOUTIAO
			initRewardedVideoAd() {
				this.rewardedVideoAd = tt.createRewardedVideoAd({
					adUnitId: 'kqutt8ufgezzi35nqz'
				})
				
				this.rewardedVideoAd.onError(err => {
					console.log('激励视频加载失败', err)
					uni.showToast({
						title: '广告加载失败，请稍后再试',
						icon: 'none'
					})
				})
				
				this.rewardedVideoAd.onClose(res => {
					if (res && res.isEnded) {
						// 正常播放结束，重置使用次数为3次
						this.remainingUses = 3
						uni.setStorageSync('remainingUses', 3)
						uni.showToast({
							title: '获得3次免费使用机会',
							icon: 'success'
						})
						this.generateNumber()
					} else {
						// 播放中途退出，不给予奖励
						uni.showToast({
							title: '观看完整视频才能获得免费次数',
							icon: 'none'
						})
					}
				})
			},
			// #endif
			
			async handleGenerateClick() {
				if (this.remainingUses > 0) {
					// 还有免费次数
					this.remainingUses--
					uni.setStorageSync('remainingUses', this.remainingUses)
					this.generateNumber()
				} else {
					// #ifdef MP-TOUTIAO
					// 没有免费次数，展示激励视频
					uni.showModal({
						title: '提示',
						content: '今日免费次数已用完，观看一个短视频可获得3次免费使用机会',
						success: async (res) => {
							if (res.confirm) {
								try {
									await this.rewardedVideoAd.show()
								} catch (err) {
									await this.rewardedVideoAd.load()
									await this.rewardedVideoAd.show()
								}
							}
						}
					})
					// #endif
					
					// #ifndef MP-TOUTIAO
					uni.showToast({
						title: '今日免费次数已用完',
						icon: 'none'
					})
					// #endif
				}
			},
			validateMinNumber() {
				let min = parseInt(this.minNumber)
				if (isNaN(min)) {
					min = 0
				} else {
					min = Math.max(-2147483646, Math.min(min, 2147483646))
				}
				this.minNumber = min.toString()
			},
			validateMaxNumber() {
				let max = parseInt(this.maxNumber)
				if (isNaN(max)) {
					max = 10
				} else {
					max = Math.max(-2147483640, Math.min(max, 2147483647))
				}
				this.maxNumber = max.toString()
			},
			validateCount() {
				let count = parseInt(this.count)
				if (isNaN(count) || count < 1) {
					count = 1
				} else if (count > 100) {
					uni.showToast({
						title: '生成个数不能超过100',
						icon: 'none'
					})
					count = 100
				}
				this.count = count.toString()
			},
			generateNumber() {
				const min = parseInt(this.minNumber) || 0
				const max = parseInt(this.maxNumber) || 10
				const count = parseInt(this.count) || 1
				
				if (min >= max) {
					uni.showToast({
						title: '最小值必须小于最大值',
						icon: 'none'
					})
					return
				}
				
				this.currentNumbers = []
				for (let i = 0; i < count; i++) {
					const randomNum = Math.floor(Math.random() * (max - min + 1)) + min
					this.currentNumbers.push(randomNum)
				}
				
				// 添加到历史记录
				this.history.unshift({
					numbers: [...this.currentNumbers],
					timestamp: new Date().toLocaleString()
				})
				
				// 限制历史记录最多20条
				if (this.history.length > 20) {
					this.history.pop()
				}
				
				// 保存到本地存储
				uni.setStorageSync('numberHistory', this.history)
			},
			resetNumber() {
				this.currentNumbers = []
				this.minNumber = '0'
				this.maxNumber = '10'
				this.count = '1'
			},
			goToHistory() {
				uni.navigateTo({
					url: '/pages/history/history'
				})
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10px;
		height: 100vh;
		box-sizing: border-box;
	}
	
	.input-group {
		width: 80%;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 10rpx;
		margin-bottom: 30rpx;
	}
	
	.input-item {
		display: flex;
		align-items: center;
		margin: 20rpx 0;
	}
	
	.label {
		width: 160rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.input {
		flex: 1;
		height: 70rpx;
		border: 1px solid #ddd;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.number-display {
		width: 80%;
		height: 250rpx; /* 固定高度 */
		background-color: #f8f8f8;
		border-radius: 10rpx;
		padding: 20rpx;
		box-sizing: border-box;
		position: relative;
	}
	
	.number-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		padding: 10rpx;
		max-height: 100%;
		overflow-y: auto;
		align-content: flex-start;
	}
	
	.number {
		font-size: 48rpx;
		color: #333;
		font-weight: bold;
	}
	
	/* 自定义滚动条样式 */
	.number-list::-webkit-scrollbar {
		width: 6rpx;
		background-color: #f5f5f5;
	}
	
	.number-list::-webkit-scrollbar-thumb {
		background-color: #999;
		border-radius: 3rpx;
	}
	
	.usage-info {
		width: 80%;
		text-align: center;
		margin-bottom: 20rpx;
	}
	
	.usage-text {
		font-size: 28rpx;
		color: #666;
	}
	
	.button-group {
		width: 80%;
		margin: 30rpx 0;
	}
	
	.btn {
		margin: 20rpx 0;
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		font-size: 32rpx;
		border: none;
		padding: 0;
		outline: none;
		border-width: 0;
		-webkit-appearance: none;
		box-shadow: none;
	}
	
	.btn::after {
		border: none;
	}
	
	.generate {
		background-color: #007AFF;
		color: #fff;
	}
	
	.reset {
		background-color: #f0f0f0;
		color: #333;
	}
	
	.history {
		background-color: #4CD964;
		color: #fff;
	}
	
	.ad-container {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;
		background-color: #fff;
		margin: 20rpx 0;
	}
	
	.ad-text {
		color: #999;
		font-size: 28rpx;
	}
</style>
